package coupon

import (
	"OnlineRetailers/controllers/OpenId"
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/models/Admin"
	"OnlineRetailers/models/User/resMes"
	error2 "OnlineRetailers/models/errorDeal"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"time"
)

type GetAllCoupon struct {
	beego.Controller
}

func (c *GetAllCoupon) GetAllCoupon() {
	defer func() {
		c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()
	var addr = "/Coupon/GetAllCoupon"
	res := resMes.GetAllCoupon{}
	coupons := []*Admin.Coupon{}
	log := &error2.Log{}
	var err error
	var openid string = ""
	var sqlTemp string = ""
	o := orm.NewOrm()

	openidTemp := c.Ctx.Request.Header["Openid"]
	fmt.Println(openidTemp, len(openidTemp))
	if openidTemp[0] != "" {
		openid = openidTemp[0]
		err = OpenId.CheckOpenId(openid)
		//fmt.Println(ses.Admin)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
	} else {
		sqlTemp = "and `num` > 0"
	}

	sql := "select * from `coupon` where (`deadline`>? or `long`=1 ) " + sqlTemp + " order by `coupon_id` desc "
	_, err = o.Raw(sql, time.Now().Unix()).QueryRows(&coupons)

	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	for index, coupon := range coupons {
		allCoupons := resMes.AllCoupons{
			Coupons: coupon,
			Had:     false,
		}
		if openid != "" {
			sql := "select * from `w_x_user_coupons` where `w_x_user_id`=? and `coupon_id`=? "
			err = o.Raw(sql, openid, coupon.CouponId).QueryRow(&coupon)
			if err != nil && err.Error() != "<QuerySeter> no row found" {
				c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
				return
			} else if err == nil {
				allCoupons.Had = true
			}
		} else if index == 4 {
			break
		}

		res.Coupons = append(res.Coupons, &allCoupons)
	}

	res.Code = "200"
	c.Data["json"] = res

}
